<template>
  <div>
    <h1>病历信息</h1>
    <div class="save-button-container" style="float: right">
      <el-button type="primary" @click="saveMedicalRecord">保存</el-button>
    </div>
    <div class="section">
      <h2>基本信息</h2>
      <table>
        <tr>
          <th width="100px">就诊卡号</th>
          <td style="width: 700px;">{{ medicalrecordInfo.cardId }}</td>
          <th width="100px">姓名</th>
          <td style="width: 700px;">{{ medicalrecordInfo.patientName }}</td>
        </tr>
        <tr>
          <th width="100px">年龄</th>
          <td>{{ medicalrecordInfo.age }}</td>
          <th width="100px">性别</th>
          <td>
            <dict-tag :options="sys_user_sex" :value="medicalrecordInfo.patientSex"/>
          </td>
        </tr>
      </table>
    </div>
    <div class="section">
      <h2>医嘱信息</h2>
      <textarea
        v-model="medicalrecordInfo.prescription"
        placeholder="请输入医嘱"
        rows="5"
        style="width: 100%"
      ></textarea>
    </div>
    <div class="section">
      <h2>症状与诊断信息</h2>
      <table>
        <tr>
          <th width="100px">症状描述</th>
          <td>
            <el-input
              v-model="medicalrecordInfo.symptoms"
              type="textarea"
              :rows="2"
              placeholder="请输入症状描述"
              style="width: 100%"
            ></el-input>
          </td>
        </tr>
        <tr>
          <th width="100px">主要诊断</th>
          <td>
            <el-select
              v-model="medicalrecordInfo.maindiagnosis"
              placeholder="请选择主要诊断"
              style="display: inline-block; border: none; box-shadow: none"
              filterable
              remote
              :remote-method="debouncedSearchMainDiagnosis"
              :loading="loading"
            >
              <el-option
                v-for="option in mainDiagnosisOptions"
                :key="option.value"
                :label="option.label"
                :value="option.label"
              ></el-option>
            </el-select>
            <i
              class="el-icon-arrow-down"
              style="font-size: 16px; margin-left: 5px"
            ></i>
          </td>
        </tr>
        <tr v-if="showSubDiagnosis">
          <th width="100px">次要诊断</th>
          <td>
            <el-select
              v-model="medicalrecordInfo.maindiagnosiscode"
              placeholder="请选择次要诊断"
              style="display: inline-block; border: none; box-shadow: none"
            >
              <el-option
                v-for="option in subDiagnosisOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
            <i
              class="el-icon-arrow-down"
              style="font-size: 16px; margin-left: 5px"
            ></i>
            <button @click="removeSubDiagnosis" class="delete-btn">删除</button>
          </td>
        </tr>
        <tr v-if="!showSubDiagnosis">
          <th></th>
          <td>
            <button @click="addSubDiagnosis" class="add-diagnosis-btn">
              新增次要诊断
            </button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElButton, ElSelect, ElOption, ElMessage} from "element-plus";
import { getMedicalrecord, updateMedicalrecord, getMainDiagnosis } from "@/api/medicalrecord/medicalrecord";
import { debounce } from "lodash";

const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict('sys_user_sex');
const medicalrecordInfo = ref({});
const loading = ref(false);

const props = defineProps({
  clinicId: String,
});

const mainDiagnosisOptions = ref([]);
const subDiagnosisOptions = ref([]);

const showSubDiagnosis = ref(false);

/** 查询病历信息 */
async function getList(clinicId) {
  if (!clinicId) {
    console.error("clinicId is required");
    return;
  }
  try {
    loading.value = true;
    const response = await getMedicalrecord(clinicId);
    medicalrecordInfo.value = response.data || {};
    loading.value = false;
  } catch (error) {
    console.error("Failed to fetch medicalrecord info:", error);
    loading.value = false;
  }
}

/** 查询主要诊断 */
async function getMainDiagnosisData(keyword = '') {
  try {
    loading.value = true;
    const response = await getMainDiagnosis(keyword);
    const data = response.rows || []; // 从 response.rows 中提取数据
    mainDiagnosisOptions.value = data.map((item) => ({
      value: item.id,
      label: item.name,
    }));
    loading.value = false;
  } catch (error) {
    console.error("Failed to fetch main diagnosis:", error);
    loading.value = false;
  }
}

/** 搜索主要诊断（防抖处理） */
const debouncedSearchMainDiagnosis = debounce((keyword) => {
  getMainDiagnosisData(keyword);
}, 300); // 300ms 的防抖时间

/** 保存病历信息 */
async function saveMedicalRecord() {
  try {
    loading.value = true;
    const response = await updateMedicalrecord(medicalrecordInfo.value);
    console.log('Medical record saved:', response);
    ElMessage.success('病历信息保存成功'); // 显示成功提示
    loading.value = false;
  } catch (error) {
    console.error('Failed to save medical record:', error);
    ElMessage.error('保存失败，请稍后再试'); // 显示失败提示
    loading.value = false;
  }
}
watch(
  () => props.clinicId,
  async (newId) => {
    if (newId) {
      await getList(newId);
    }
  },
  { immediate: true } // 立即执行一次
);

// 在组件加载时调用
onMounted(() => {
  if (props.clinicId) {
    getList(props.clinicId);
  }
  getMainDiagnosisData(); // 获取初始的主要诊断数据
});

function addSubDiagnosis() {
  showSubDiagnosis.value = true;
}

function removeSubDiagnosis() {
  showSubDiagnosis.value = false;
}
</script>

<style scoped>
body {
  font-family: "Microsoft YaHei", Arial, sans-serif;
  margin: 20px;
  font-size: 16px;
  color: #333;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
}

h2 {
  font-size: 18px;
  color: #333;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-sizing: border-box;
}

th {
  background-color: #f2f2f2;
  text-align: center;
  width: 120px;
}

td {
  width: auto; /* 默认自动宽度 */
}

.section {
  margin-bottom: 20px;
}

.save-button-container {
  text-align: center;
}

.add-diagnosis-btn {
  margin-top: 10px;
  background-color: #007bff;
  color: white;
  padding: 6px 12px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 14px;
}

.add-diagnosis-btn:hover {
  background-color: #0056b3;
}

.delete-btn {
  background-color: #dc3545;
  color: white;
  padding: 4px 8px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  margin-left: 5px;
}

.delete-btn:hover {
  background-color: #c82333;
}
</style>